<template>
  <div class="exam-management-container">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>考试管理</h1>
        <p>管理课程考试和测验</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          创建考试
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="课程">
          <el-select v-model="filterForm.courseId" placeholder="选择课程" clearable style="width: 200px">
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试类型">
          <el-select v-model="filterForm.examType" placeholder="选择类型" clearable style="width: 150px">
            <el-option label="随堂练习" value="QUIZ" />
            <el-option label="期中考试" value="MIDTERM" />
            <el-option label="期末考试" value="FINAL" />
            <el-option label="模拟练习" value="PRACTICE" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="草稿" value="DRAFT" />
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="已归档" value="ARCHIVED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索考试标题"
            style="width: 200px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadExams">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 考试列表 -->
    <div class="exams-section">
      <el-table v-loading="loading" :data="exams" stripe>
        <el-table-column prop="title" label="考试标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="courseName" label="所属课程" width="150" />
        <el-table-column prop="examType" label="考试类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExamTypeColor(row.examType)">
              {{ getExamTypeText(row.examType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalPoints" label="总分" width="80" />
        <el-table-column prop="timeLimit" label="时长" width="80">
          <template #default="{ row }">
            {{ row.timeLimit ? `${row.timeLimit}分钟` : '不限时' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="participantCount" label="参与人数" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="420" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewExam(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="editExam(row)">
              编辑
            </el-button>
            <el-button v-if="row.status === 'DRAFT'" type="success" size="small" @click="publishExam(row)">
              发布
            </el-button>
            <el-button v-if="row.status === 'PUBLISHED'" type="info" size="small" @click="archiveExam(row)">
              归档
            </el-button>
            <el-button size="small" @click="loadStats(row)" plain>
              统计
            </el-button>
            <el-button type="danger" size="small" @click="deleteExam(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建/编辑考试对话框 -->
    <el-dialog
      v-model="showExamDialog"
      :title="dialogTitle"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form :model="examForm" :rules="examRules" ref="examFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属课程" prop="courseId">
              <el-select v-model="examForm.courseId" placeholder="选择课程" style="width: 100%">
                <el-option
                  v-for="course in courses"
                  :key="course.id"
                  :label="course.title"
                  :value="course.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试类型" prop="examType">
              <el-select v-model="examForm.examType" style="width: 100%">
                <el-option label="随堂练习" value="QUIZ" />
                <el-option label="期中考试" value="MIDTERM" />
                <el-option label="期末考试" value="FINAL" />
                <el-option label="模拟练习" value="PRACTICE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="考试标题" prop="title">
          <el-input v-model="examForm.title" placeholder="请输入考试标题" />
        </el-form-item>
        
        <el-form-item label="考试描述">
          <el-input
            v-model="examForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入考试描述和注意事项"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="考试时长" prop="timeLimit">
              <el-input-number
                v-model="examForm.timeLimit"
                :min="0"
                :max="480"
                placeholder="分钟"
                style="width: 100%"
              />
              <div class="form-tip">设置为0表示不限时</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="及格分数" prop="passScore">
              <el-input-number
                v-model="examForm.passScore"
                :min="0"
                :max="100"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="允许次数" prop="maxAttempts">
              <el-input-number
                v-model="examForm.maxAttempts"
                :min="1"
                :max="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="examForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="examForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="考试设置">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-checkbox v-model="examForm.showResult">显示成绩</el-checkbox>
            </el-col>
            <el-col :span="6">
              <el-checkbox v-model="examForm.showCorrectAnswers">显示答案</el-checkbox>
            </el-col>
            <el-col :span="6">
              <el-checkbox v-model="examForm.shuffleQuestions">题目乱序</el-checkbox>
            </el-col>
            <el-col :span="6">
              <el-checkbox v-model="examForm.shuffleOptions">选项乱序</el-checkbox>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 选题区域 -->
        <el-form-item label="考试题目">
          <div class="questions-selector">
            <div class="selector-header">
              <el-button type="primary" @click="showQuestionSelector = true">
                选择题目
              </el-button>
              <el-button @click="openImportDialog">批量导入</el-button>
              <span class="question-count">
                已选择 {{ selectedQuestions.length }} 道题目，总分 {{ totalPoints }} 分
              </span>
              <div>
                <el-button 
                  :disabled="selectedQuestions.length === 0" 
                  @click="previewSelectedQuestions" 
                  type="info"
                >预览</el-button>
              </div>
            </div>
            
            <div v-if="selectedQuestions.length > 0" class="selected-questions">
              <draggable 
                v-model="selectedQuestions" 
                item-key="id" 
                handle=".drag-handle" 
                animation="200"
              >
                <template #item="{ element: question, index }">
                  <div class="question-item">
                    <div class="question-info">
                      <span class="drag-handle" title="拖拽调整顺序">
                        <el-icon><Rank /></el-icon>
                      </span>
                      <span class="question-number">{{ index + 1 }}.</span>
                      <span class="question-title">{{ question.title }}</span>
                      <el-tag size="small" :type="getQuestionTypeColor(question.questionType)">
                        {{ getQuestionTypeText(question.questionType) }}
                      </el-tag>
                      <span class="question-points">{{ question.points }}分</span>
                    </div>
                    <el-button size="small" type="danger" @click="removeQuestion(index)">
                      移除
                    </el-button>
                  </div>
                </template>
              </draggable>
            </div>
            
            <div v-else class="empty-questions">
              <p>请选择考试题目</p>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showExamDialog = false">取消</el-button>
        <el-button 
          :disabled="selectedQuestions.length === 0" 
          @click="previewSelectedQuestions"
        >预览</el-button>
        <el-button type="primary" @click="saveExam" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 题目选择器 -->
    <el-dialog v-model="showQuestionSelector" title="选择题目" width="1000px" append-to-body>
      <div class="question-selector-content">
        <!-- 筛选条件 -->
        <el-form :model="questionFilter" inline style="margin-bottom: 20px">
          <el-form-item label="课程">
            <el-select v-model="questionFilter.courseId" placeholder="选择课程" style="width: 200px">
              <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.title"
                :value="course.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题型">
            <el-select v-model="questionFilter.questionType" placeholder="选择题型" clearable style="width: 150px">
              <el-option label="单选题" value="SINGLE_CHOICE" />
              <el-option label="多选题" value="MULTIPLE_CHOICE" />
              <el-option label="判断题" value="TRUE_FALSE" />
              <el-option label="填空题" value="FILL_BLANK" />
              <el-option label="问答题" value="ESSAY" />
            </el-select>
          </el-form-item>
          <el-form-item label="难度">
            <el-select v-model="questionFilter.difficulty" placeholder="选择难度" clearable style="width: 120px">
              <el-option label="简单" value="EASY" />
              <el-option label="中等" value="MEDIUM" />
              <el-option label="困难" value="HARD" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadAvailableQuestions">搜索</el-button>
          </el-form-item>
        </el-form>

        <!-- 题目列表 -->
        <el-table
          :data="availableQuestions"
          @selection-change="handleQuestionSelection"
          height="400px"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="title" label="题目标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="questionType" label="题型" width="100">
            <template #default="{ row }">
              <el-tag size="small" :type="getQuestionTypeColor(row.questionType)">
                {{ getQuestionTypeText(row.questionType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="80">
            <template #default="{ row }">
              <el-tag size="small" :type="getDifficultyColor(row.difficulty)">
                {{ getDifficultyText(row.difficulty) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="points" label="分值" width="80" />
        </el-table>
      </div>

      <template #footer>
        <el-button @click="showQuestionSelector = false">取消</el-button>
        <el-button type="primary" @click="confirmQuestionSelection">确定选择</el-button>
      </template>
    </el-dialog>

    <!-- 查看考试详情对话框 -->
    <el-dialog v-model="showViewDialog" title="考试详情" width="800px">
      <div v-if="selectedExam" class="exam-detail">
        <div class="detail-section">
          <h3>基本信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <label>考试标题：</label>
              <span>{{ selectedExam.title }}</span>
            </div>
            <div class="detail-item">
              <label>所属课程：</label>
              <span>{{ selectedExam.courseName }}</span>
            </div>
            <div class="detail-item">
              <label>考试类型：</label>
              <el-tag :type="getExamTypeColor(selectedExam.examType)">
                {{ getExamTypeText(selectedExam.examType) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>考试状态：</label>
              <el-tag :type="getStatusColor(selectedExam.status)">
                {{ getStatusText(selectedExam.status) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>总分：</label>
              <span>{{ selectedExam.totalPoints }} 分</span>
            </div>
            <div class="detail-item">
              <label>及格分：</label>
              <span>{{ selectedExam.passScore }} 分</span>
            </div>
            <div class="detail-item">
              <label>考试时长：</label>
              <span>{{ selectedExam.timeLimit ? `${selectedExam.timeLimit} 分钟` : '不限时' }}</span>
            </div>
            <div class="detail-item">
              <label>允许次数：</label>
              <span>{{ selectedExam.maxAttempts }} 次</span>
            </div>
          </div>
        </div>

        <div v-if="selectedExam.description" class="detail-section">
          <h3>考试描述</h3>
          <div class="description">{{ selectedExam.description }}</div>
        </div>

        <div class="detail-section">
          <h3>考试设置</h3>
          <div class="settings-grid">
            <div class="setting-item">
              <el-icon><Check /></el-icon>
              <span :class="{ disabled: !selectedExam.showResult }">显示成绩</span>
            </div>
            <div class="setting-item">
              <el-icon><Check /></el-icon>
              <span :class="{ disabled: !selectedExam.showCorrectAnswers }">显示答案</span>
            </div>
            <div class="setting-item">
              <el-icon><Check /></el-icon>
              <span :class="{ disabled: !selectedExam.shuffleQuestions }">题目乱序</span>
            </div>
            <div class="setting-item">
              <el-icon><Check /></el-icon>
              <span :class="{ disabled: !selectedExam.shuffleOptions }">选项乱序</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h3>统计信息</h3>
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-number">{{ (selectedExam as any).participantCount || 0 }}</div>
              <div class="stat-label">参与人数</div>
            </div>
            <div class="stat-card">
              <div class="stat-number">{{ (selectedExam as any).avgScore || 0 }}</div>
              <div class="stat-label">平均分</div>
            </div>
            <div class="stat-card">
              <div class="stat-number">{{ (selectedExam as any).passRate || 0 }}%</div>
              <div class="stat-label">及格率</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 考试统计对话框 -->
    <el-dialog v-model="showStatsDialog" title="考试统计" width="700px">
      <div v-if="examStats">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="参与人数">{{ examStats.participantCount }}</el-descriptions-item>
          <el-descriptions-item label="记录数">{{ examStats.recordCount }}</el-descriptions-item>
          <el-descriptions-item label="平均分">{{ examStats.averageScore?.toFixed ? examStats.averageScore.toFixed(2) : examStats.averageScore }}</el-descriptions-item>
          <el-descriptions-item label="平均正确率">{{ examStats.averagePercentage }}%</el-descriptions-item>
          <el-descriptions-item label="通过人数">{{ examStats.passCount }}</el-descriptions-item>
          <el-descriptions-item label="未通过人数">{{ examStats.failCount }}</el-descriptions-item>
          <el-descriptions-item label="通过率" :span="2">{{ examStats.passRate }}%</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="showStatsDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框：用于查看已选题目或已存在考试的题目 -->
    <el-dialog v-model="showPreviewDialog" :title="previewTitle" width="900px">
      <div v-if="previewQuestions.length === 0" style="padding: 20px; color: #909399;">暂无题目</div>
      <div v-else class="preview-questions">
        <div v-for="(q, idx) in previewQuestions" :key="q.id || q.questionId" class="preview-question">
          <div class="preview-q-header">
            <span class="preview-q-number">{{ idx + 1 }}.</span>
            <span class="preview-q-title">{{ q.title }}</span>
            <el-tag size="small" :type="getQuestionTypeColor(q.questionType)">{{ getQuestionTypeText(q.questionType) }}</el-tag>
            <span class="preview-q-points">{{ q.points }}分</span>
          </div>
          <ul v-if="Array.isArray(q.options) && q.options.length" class="preview-q-options">
            <li v-for="(opt, oi) in q.options" :key="oi">{{ optionLabel(oi) }}. {{ typeof opt === 'string' ? opt : (opt.content || JSON.stringify(opt)) }}</li>
          </ul>
        </div>
      </div>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog v-model="showImportDialog" title="批量导入题目 (CSV/JSON)" width="900px" :close-on-click-modal="false">
      <div class="import-container">
        <el-alert 
          v-if="!examForm.courseId" 
          title="请先在考试表单选择所属课程，否则无法保存到题库" 
          type="warning" show-icon style="margin-bottom: 12px;"/>
        <div class="import-controls">
          <el-radio-group v-model="importFormat" size="small">
            <el-radio-button label="CSV" />
            <el-radio-button label="JSON" />
          </el-radio-group>
          <input type="file" @change="onImportFileChange" accept=".csv,.json" />
          <el-button @click="parseImportText" :disabled="!rawImportText">解析</el-button>
        </div>
        <el-input v-model="rawImportText" type="textarea" :rows="8" placeholder="可直接粘贴文件内容到此处，然后点击解析" />

        <div class="import-preview" v-if="parsedImport.length">
          <div class="import-summary">共解析到 {{ parsedImport.length }} 题；有效 {{ validImport.length }} 题</div>
          <el-table :data="parsedImport" height="260" :row-class-name="(data: any) => (data.row._valid ? '' : 'row-invalid')">
            <el-table-column type="index" width="50" label="#" />
            <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
            <el-table-column prop="questionType" label="题型" width="120" />
            <el-table-column prop="difficulty" label="难度" width="90" />
            <el-table-column prop="points" label="分值" width="80" />
            <el-table-column prop="_error" label="校验" min-width="180" />
          </el-table>
        </div>
        <div class="import-actions" style="margin-top: 12px;">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button type="primary" :disabled="!validImport.length || !examForm.courseId" @click="saveImportedToBank">
            保存到题库并添加到本次考试
          </el-button>
        </div>
        <el-divider />
        <details>
          <summary>CSV 模板示例（逗号分隔，首行为表头）</summary>
          <pre style="white-space: pre-wrap;">title,content,questionType,options,correctAnswers,difficulty,points
计算机基础,CPU 的全称是？,SINGLE_CHOICE,"A=中央处理器|B=图形处理器|C=内存|D=硬盘",A,EASY,5
网络基础,以下哪些属于网络协议？,MULTIPLE_CHOICE,"A=HTTP|B=DNS|C=FTP|D=SSD","A|B|C",MEDIUM,10
判断题示例,JavaScript 是强类型语言。,TRUE_FALSE,,,EASY,2
          </pre>
        </details>
        <details>
          <summary>JSON 模板示例（数组）</summary>
          <pre style="white-space: pre-wrap;">[
  {"title":"计算机基础","content":"CPU 的全称是？","questionType":"SINGLE_CHOICE","options":{"A":"中央处理器","B":"图形处理器","C":"内存","D":"硬盘"},"correctAnswers":["A"],"difficulty":"EASY","points":5},
  {"title":"网络基础","content":"以下哪些属于网络协议？","questionType":"MULTIPLE_CHOICE","options":{"A":"HTTP","B":"DNS","C":"FTP","D":"SSD"},"correctAnswers":["A","B","C"],"difficulty":"MEDIUM","points":10},
  {"title":"判断题示例","content":"JavaScript 是强类型语言。","questionType":"TRUE_FALSE","correctAnswers":[false],"difficulty":"EASY","points":2}
]
          </pre>
        </details>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Check, View, Rank } from '@element-plus/icons-vue'
import { examApi, questionApi, type Exam, type ExamRequest, type Question, type ExamStats } from '@/api/exam'
import { courseApi, type Course } from '@/api/course'
import draggable from 'vuedraggable'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const exams = ref<Exam[]>([])
const courses = ref<Course[]>([])
const availableQuestions = ref<Question[]>([])
const selectedQuestions = ref<Question[]>([])
const tempSelectedQuestions = ref<Question[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const showExamDialog = ref(false)
const showCreateDialog = ref(false)
const showQuestionSelector = ref(false)
const showViewDialog = ref(false)
const selectedExam = ref<Exam>()
const examFormRef = ref()

// 预览
const showPreviewDialog = ref(false)
const previewQuestions = ref<any[]>([])
const previewTitle = ref('预览')

// 导入
const showImportDialog = ref(false)
const importFormat = ref<'CSV'|'JSON'>('CSV')
const rawImportText = ref('')
const parsedImport = ref<any[]>([])
const validImport = computed(() => parsedImport.value.filter(q => q._valid))

// 统计
const showStatsDialog = ref(false)
const examStats = ref<ExamStats | null>(null)

// 筛选表单
const filterForm = reactive({
  courseId: undefined as number | undefined,
  examType: '',
  status: '',
  keyword: ''
})

// 题目筛选
const questionFilter = reactive({
  courseId: undefined as number | undefined,
  questionType: '',
  difficulty: ''
})

// 考试表单
const examForm = reactive({
  id: undefined as number | undefined,
  courseId: 0,
  title: '',
  description: '',
  examType: 'QUIZ' as 'QUIZ' | 'MIDTERM' | 'FINAL' | 'PRACTICE',
  timeLimit: 60,
  passScore: 60,
  maxAttempts: 1,
  startTime: '',
  endTime: '',
  showResult: true,
  showCorrectAnswers: false,
  shuffleQuestions: false,
  shuffleOptions: false,
  totalPoints: 0,
  questions: [] as Array<{
    questionId: number
    orderNo: number
    points: number
  }>
})

// 表单验证规则
const examRules = {
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  title: [{ required: true, message: '请输入考试标题', trigger: 'blur' }],
  examType: [{ required: true, message: '请选择考试类型', trigger: 'change' }],
  passScore: [{ required: true, message: '请输入及格分数', trigger: 'blur' }],
  maxAttempts: [{ required: true, message: '请输入允许次数', trigger: 'blur' }]
}

// 计算属性
const dialogTitle = ref('创建考试')
const totalPoints = computed(() => {
  return selectedQuestions.value.reduce((sum, q) => sum + q.points, 0)
})

const optionLabel = (index: number) => {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  return alphabet[index] || String(index + 1)
}

// 工具函数
// 日期时间格式化函数
const formatDateTime = (dateTimeString: string) => {
  if (!dateTimeString) return null
  const date = new Date(dateTimeString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const getExamTypeText = (type: string) => {
  const typeMap = {
    QUIZ: '随堂练习',
    MIDTERM: '期中考试',
    FINAL: '期末考试',
    PRACTICE: '模拟练习'
  }
  return typeMap[type as keyof typeof typeMap] || type
}

const getExamTypeColor = (type: string) => {
  const colorMap = {
    QUIZ: 'primary',
    MIDTERM: 'success',
    FINAL: 'danger',
    PRACTICE: 'warning'
  }
  return colorMap[type as keyof typeof colorMap] || ''
}

const getStatusText = (status: string) => {
  const statusMap = {
    DRAFT: '草稿',
    PUBLISHED: '已发布',
    ARCHIVED: '已归档'
  }
  return statusMap[status as keyof typeof statusMap] || status
}

const getStatusColor = (status: string) => {
  const colorMap = {
    DRAFT: 'info',
    PUBLISHED: 'success',
    ARCHIVED: 'warning'
  }
  return colorMap[status as keyof typeof colorMap] || ''
}

const getQuestionTypeText = (type: string) => {
  const typeMap = {
    SINGLE_CHOICE: '单选题',
    MULTIPLE_CHOICE: '多选题',
    TRUE_FALSE: '判断题',
    FILL_BLANK: '填空题',
    ESSAY: '问答题'
  }
  return typeMap[type as keyof typeof typeMap] || type
}

const getQuestionTypeColor = (type: string) => {
  const colorMap = {
    SINGLE_CHOICE: 'primary',
    MULTIPLE_CHOICE: 'success',
    TRUE_FALSE: 'warning',
    FILL_BLANK: 'info',
    ESSAY: 'danger'
  }
  return colorMap[type as keyof typeof colorMap] || ''
}

const getDifficultyText = (difficulty: string) => {
  const difficultyMap = {
    EASY: '简单',
    MEDIUM: '中等',
    HARD: '困难'
  }
  return difficultyMap[difficulty as keyof typeof difficultyMap] || difficulty
}

const getDifficultyColor = (difficulty: string) => {
  const colorMap = {
    EASY: 'success',
    MEDIUM: 'warning',
    HARD: 'danger'
  }
  return colorMap[difficulty as keyof typeof colorMap] || ''
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 页面方法
const loadCourses = async () => {
  try {
    const res = await courseApi.getTeacherCourses({ page: 1, pageSize: 100 })
    courses.value = res.content || []
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

const loadExams = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      courseId: filterForm.courseId || undefined,
      examType: filterForm.examType || undefined,
      status: filterForm.status || undefined,
      keyword: filterForm.keyword || undefined
    }
    const res = await examApi.search(params)
    exams.value = res.content || []
    total.value = res.totalElements || 0
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  } finally {
    loading.value = false
  }
}

const loadAvailableQuestions = async () => {
  try {
    // 如果没有选择课程，使用第一个课程
    if (!questionFilter.courseId && courses.value.length > 0) {
      questionFilter.courseId = courses.value[0].id
    }
    
    const params = {
      page: 1,
      pageSize: 100,
      courseId: questionFilter.courseId || undefined,
      questionType: questionFilter.questionType || undefined,
      difficulty: questionFilter.difficulty || undefined
    }
    
    console.log('考试题目查询参数:', params)
    // 使用正确的API调用
    const res = await questionApi.search(params)
    console.log('考试题目查询响应:', res)
    
    // 处理返回的数据，将JSON字符串解析为数组
    const processedQuestions = ((res as any).content || []).map((question: any) => {
      if (typeof question.options === 'string' && question.options) {
        try {
          question.options = JSON.parse(question.options)
        } catch (e) {
          question.options = []
        }
      }
      if (typeof question.correctAnswers === 'string' && question.correctAnswers) {
        try {
          question.correctAnswers = JSON.parse(question.correctAnswers)
        } catch (e) {
          question.correctAnswers = []
        }
      }
      return question
    })
    
    availableQuestions.value = processedQuestions
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
  }
}

const resetFilter = () => {
  filterForm.courseId = undefined
  filterForm.examType = ''
  filterForm.status = ''
  filterForm.keyword = ''
  loadExams()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  loadExams()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadExams()
}

// 考试操作
const viewExam = (exam: Exam) => {
  selectedExam.value = exam
  showViewDialog.value = true
}

// 加载考试题目
const loadExamQuestions = async (examId: number) => {
  try {
    const res = await examApi.getExamQuestions(examId)
    // 将考试题目转换为选中的题目格式
    selectedQuestions.value = (res as any[]).map((q: any) => ({
      id: q.questionId || q.id,
      title: q.title,
      questionType: q.questionType,
      difficulty: q.difficulty,
      points: q.points,
      content: q.content,
      options: q.options,
      correctAnswers: q.correctAnswers,
      explanation: q.explanation,
      courseId: q.courseId || 0,
      createdBy: q.createdBy || 0,
      createdAt: q.createdAt || '',
      updatedAt: q.updatedAt || ''
    } as Question))
  } catch (error) {
    console.error('加载考试题目失败:', error)
    selectedQuestions.value = []
  }
}

const editExam = (exam: Exam) => {
  // 填充表单数据
  Object.assign(examForm, {
    id: exam.id,
    courseId: exam.courseId,
    title: exam.title,
    description: exam.description,
    examType: exam.examType,
    timeLimit: exam.timeLimit,
    passScore: exam.passScore,
    maxAttempts: exam.maxAttempts,
    startTime: exam.startTime,
    endTime: exam.endTime,
    showResult: exam.showResult,
    showCorrectAnswers: exam.showCorrectAnswers,
    shuffleQuestions: exam.shuffleQuestions,
    shuffleOptions: exam.shuffleOptions
  })
  
  // 加载考试题目
  loadExamQuestions(exam.id)
  
  dialogTitle.value = '编辑考试'
  showExamDialog.value = true
}

const previewExam = async (exam: Exam) => {
  try {
    previewTitle.value = `预览：${exam.title}`
    const res = await examApi.getExamQuestions(exam.id)
    previewQuestions.value = res || []
    showPreviewDialog.value = true
  } catch (error) {
    ElMessage.error('加载预览失败')
  }
}

const publishExam = async (exam: Exam) => {
  try {
    await ElMessageBox.confirm(
      `确定要发布考试"${exam.title}"吗？发布后学生可以参加考试。`,
      '发布确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('发布考试，考试ID:', exam.id)
    console.log('当前用户Token:', localStorage.getItem('access_token'))
    await examApi.publish(exam.id)
    ElMessage.success('发布成功')
    loadExams()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布考试失败:', error)
      ElMessage.error('发布考试失败')
    }
  }
}

const archiveExam = async (exam: Exam) => {
  try {
    await ElMessageBox.confirm(
      `确定要归档考试"${exam.title}"吗？归档后学生无法继续参加考试。`,
      '归档确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await examApi.archive(exam.id)
    ElMessage.success('归档成功')
    loadExams()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('归档考试失败:', error)
      ElMessage.error('归档考试失败')
    }
  }
}

const deleteExam = async (exam: Exam) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除考试"${exam.title}"吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await examApi.delete(exam.id)
    ElMessage.success('删除成功')
    loadExams()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除考试失败:', error)
      ElMessage.error('删除考试失败')
    }
  }
}

// 题目选择
const handleQuestionSelection = (selection: Question[]) => {
  tempSelectedQuestions.value = selection
}

const confirmQuestionSelection = () => {
  // 过滤掉无效的题目（没有ID或分数的题目）
  const validQuestions = tempSelectedQuestions.value.filter(q => q.id && q.points && q.points > 0)
  
  if (validQuestions.length !== tempSelectedQuestions.value.length) {
    ElMessage.warning(`已过滤 ${tempSelectedQuestions.value.length - validQuestions.length} 个无效题目`)
  }
  
  selectedQuestions.value = [...validQuestions]
  showQuestionSelector.value = false
}

const removeQuestion = (index: number) => {
  selectedQuestions.value.splice(index, 1)
}

const previewSelectedQuestions = () => {
  if (selectedQuestions.value.length === 0) return
  previewTitle.value = `预览：${examForm.title || '未命名考试'}`
  previewQuestions.value = selectedQuestions.value
  showPreviewDialog.value = true
}

const loadStats = async (exam: Exam) => {
  try {
    const stats = await examApi.getStats(exam.id)
    examStats.value = {
      ...stats,
      averagePercentage: Number(stats.averagePercentage || 0)
    } as any
    showStatsDialog.value = true
  } catch (e: any) {
    ElMessage.error('加载统计失败')
  }
}

// 批量导入
const openImportDialog = () => {
  showImportDialog.value = true
  rawImportText.value = ''
  parsedImport.value = []
}

const onImportFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return
  const reader = new FileReader()
  reader.onload = () => {
    rawImportText.value = String(reader.result || '')
  }
  reader.readAsText(file, 'utf-8')
}

const parseImportText = () => {
  if (!rawImportText.value.trim()) {
    ElMessage.warning('请粘贴或选择文件后再解析')
    return
  }
  try {
    if (importFormat.value === 'JSON') {
      const data = JSON.parse(rawImportText.value)
      parsedImport.value = Array.isArray(data) ? data.map(sanitizeImportedItem) : []
    } else {
      parsedImport.value = parseCsv(rawImportText.value).map(sanitizeImportedItem)
    }
    ElMessage.success(`解析完成，共 ${parsedImport.value.length} 条`)
  } catch (e: any) {
    console.error('解析失败:', e)
    ElMessage.error('解析失败，请检查格式')
  }
}

const parseCsv = (text: string) => {
  const lines = text.split(/\r?\n/).filter(l => l.trim())
  if (lines.length <= 1) return []
  const headers = lines[0].split(',').map(h => h.trim())
  const rows = lines.slice(1)
  const items = rows.map(line => {
    const cols = splitCsvLine(line)
    const obj: Record<string, string> = {}
    headers.forEach((h, i) => obj[h] = (cols[i] ?? '').trim())
    return {
      title: obj.title,
      content: obj.content,
      questionType: obj.questionType,
      options: parseCsvOptions(obj.options),
      correctAnswers: parseCsvAnswers(obj.correctAnswers),
      difficulty: obj.difficulty || 'MEDIUM',
      points: Number(obj.points || 1)
    }
  })
  return items
}

const splitCsvLine = (line: string): string[] => {
  const out: string[] = []
  let cur = ''
  let inQuotes = false
  for (let i = 0; i < line.length; i++) {
    const ch = line[i]
    if (ch === '"') {
      inQuotes = !inQuotes
    } else if (ch === ',' && !inQuotes) {
      out.push(cur)
      cur = ''
    } else {
      cur += ch
    }
  }
  out.push(cur)
  return out
}

const parseCsvOptions = (s?: string) => {
  if (!s) return undefined
  // 形如 A=文本|B=文本
  const map: Record<string, string> = {}
  s.split('|').forEach(pair => {
    const [k, v] = pair.split('=')
    if (k && v) map[k.trim()] = v.trim()
  })
  return map
}

const parseCsvAnswers = (s?: string) => {
  if (!s) return []
  // 形如 A|B 或 TRUE/FALSE
  const val = s.trim()
  if (/^(true|false)$/i.test(val)) {
    return [String(/^true$/i.test(val) ? true : false)]
  }
  return val.split('|').map(x => x.trim()).filter(Boolean)
}

const sanitizeImportedItem = (q: any) => {
  const item: any = {
    title: String(q.title || '').trim(),
    content: String(q.content || '').trim(),
    questionType: String(q.questionType || '').toUpperCase(),
    options: q.options,
    correctAnswers: Array.isArray(q.correctAnswers) ? q.correctAnswers : (q.correctAnswers ? [q.correctAnswers] : []),
    difficulty: (String(q.difficulty || 'MEDIUM').toUpperCase()),
    points: Number(q.points || 1)
  }
  // 校验
  const errors: string[] = []
  if (!item.title) errors.push('缺少标题')
  if (!['SINGLE_CHOICE','MULTIPLE_CHOICE','TRUE_FALSE','FILL_BLANK','ESSAY'].includes(item.questionType)) errors.push('题型不合法')
  if ((item.questionType === 'SINGLE_CHOICE' || item.questionType === 'MULTIPLE_CHOICE') && !item.options) errors.push('缺少选项')
  if (item.points <= 0) errors.push('分值必须>0')
  item._valid = errors.length === 0
  item._error = errors.join('；')
  return item
}

const saveImportedToBank = async () => {
  if (!examForm.courseId) {
    ElMessage.warning('请先选择考试所属课程')
    return
  }
  const toSave = validImport.value
  if (!toSave.length) {
    ElMessage.warning('没有可保存的有效题目')
    return
  }
  try {
    const created: Question[] = []
    for (const q of toSave) {
      const req = {
        courseId: examForm.courseId,
        title: q.title,
        content: q.content || '',
        questionType: q.questionType,
        options: q.options || undefined,
        correctAnswers: q.correctAnswers,
        difficulty: q.difficulty || 'MEDIUM',
        points: q.points || 1
      }
      const res = await questionApi.create(req)
      created.push(res as unknown as Question)
    }
    // 合并到当前选择，确保数据完整性
    created.forEach((q) => {
      if (q.id && q.points && q.points > 0) {
        selectedQuestions.value.push({
          id: q.id,
          title: q.title,
          questionType: q.questionType,
          difficulty: q.difficulty,
          points: q.points,
          content: q.content,
          options: q.options,
          correctAnswers: q.correctAnswers,
          explanation: q.explanation
        } as any)
      } else {
        console.warn('跳过无效题目:', q)
      }
    })
    showImportDialog.value = false
    ElMessage.success(`已导入并添加 ${created.length} 题`)
  } catch (e) {
    console.error('保存导入题目失败:', e)
    ElMessage.error('保存导入题目失败')
  }
}

// 保存考试
const saveExam = async () => {
  try {
    await examFormRef.value.validate()
    
    if (selectedQuestions.value.length === 0) {
      ElMessage.error('请选择考试题目')
      return
    }
    
    // 更新总分和题目
    examForm.totalPoints = totalPoints.value

    if (!examForm.totalPoints || examForm.totalPoints <= 0) {
      ElMessage.error('考试总分必须大于0')
      return
    }
    
    // 验证题目数据完整性
    const invalidQuestions = selectedQuestions.value.filter(q => !q.id || !q.points || q.points <= 0)
    if (invalidQuestions.length > 0) {
      ElMessage.error('存在无效题目数据，请重新选择题目')
      console.error('无效题目:', invalidQuestions)
      return
    }

    // 准备提交数据，包含题目信息（移除id字段，通过URL传递）
    const submitData = {
      courseId: examForm.courseId,
      title: examForm.title,
      description: examForm.description,
      examType: examForm.examType,
      timeLimit: examForm.timeLimit,
      passScore: examForm.passScore,
      maxAttempts: examForm.maxAttempts,
      startTime: examForm.startTime ? formatDateTime(examForm.startTime) || undefined : undefined,
      endTime: examForm.endTime ? formatDateTime(examForm.endTime) || undefined : undefined,
      showResult: examForm.showResult,
      showCorrectAnswers: examForm.showCorrectAnswers,
      shuffleQuestions: examForm.shuffleQuestions,
      shuffleOptions: examForm.shuffleOptions,
      totalPoints: examForm.totalPoints,
      questions: selectedQuestions.value.map((q, index) => ({
        questionId: q.id,
        orderNo: index + 1,
        points: q.points
      }))
    }
    
    console.log('保存考试数据:', submitData)
    saving.value = true
    
    if (examForm.id) {
      await examApi.update(examForm.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await examApi.create(submitData)
      ElMessage.success('创建成功')
    }
    
    showExamDialog.value = false
    loadExams()
  } catch (error: any) {
    console.error('保存考试失败:', error)
    console.error('错误详情:', error.response?.data)
    
    // 提取具体的错误信息
    let errorMessage = '保存考试失败'
    if (error.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetExamForm = () => {
  Object.assign(examForm, {
    id: undefined,
    courseId: 0,
    title: '',
    description: '',
    examType: 'QUIZ',
    timeLimit: 60,
    passScore: 60,
    maxAttempts: 1,
    startTime: '',
    endTime: '',
    showResult: true,
    showCorrectAnswers: false,
    shuffleQuestions: false,
    shuffleOptions: false
  })
  
  selectedQuestions.value = []
}

// 监听对话框
watch(() => showCreateDialog.value, (newVal) => {
  if (newVal) {
    resetExamForm()
    dialogTitle.value = '创建考试'
    showExamDialog.value = true
    showCreateDialog.value = false
  }
})

// 监听题目选择器
watch(() => showQuestionSelector.value, (newVal) => {
  if (newVal) {
    questionFilter.courseId = examForm.courseId
    loadAvailableQuestions()
  }
})

// 页面初始化
onMounted(() => {
  loadCourses()
  loadExams()
})
</script>

<style scoped>
.exam-management-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left h1 {
  margin: 0 0 5px 0;
  font-size: 24px;
  color: #333;
}

.header-left p {
  margin: 0;
  color: #666;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.exams-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.questions-selector {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background: #fafafa;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-count {
  color: #666;
  font-size: 14px;
}

.selected-questions {
  max-height: 200px;
  overflow-y: auto;
}

.question-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-bottom: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.question-item .drag-handle {
  cursor: move;
  color: #909399;
}

.question-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.question-number {
  font-weight: bold;
  color: #409eff;
}

.question-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.question-points {
  color: #f56c6c;
  font-weight: bold;
}

.empty-questions {
  text-align: center;
  padding: 40px;
  color: #999;
}

.question-selector-content {
  max-height: 500px;
}

.exam-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 25px;
}

.detail-section h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: bold;
  color: #333;
  min-width: 80px;
  margin-right: 10px;
}

.description {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  white-space: pre-wrap;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.setting-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.setting-item span.disabled {
  color: #ccc;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.import-container .row-invalid > td {
  color: #f56c6c;
}
</style>